package com.libinyn.pdf.utils;


import com.itextpdf.text.pdf.BaseFont;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;


/**
 * pdf文件打印
 * @fileName: PrintPdfUtils.java
 * @author: bin.li01
 * @date: 2017/11/23 18:37
 * @version: v1.0.0
 */
public class PrintPdfUtils {

    private static Logger logger = LoggerFactory.getLogger(PrintPdfUtils.class);

    /**
     * 打印模板地址
     */
    private static final String PRINT_TEMPLATE_PATH = "/templates/";
    /**
     * 字体地址
     */
    private static final String PATH_TTF = "/templates/msyh.ttf";

    /**
     * 生成PDF方法
     * @param response
     * @param templateName 模板名称
     * @param printModel 模板中数据的对象
     * @throws Exception
     */
    public static void printPdf(HttpServletResponse response, String templateName, Object printModel) {
        logger.debug("pdf文件打印");

        response.setContentType("application/pdf");
        //print.pdf 是生成的文件名称
        response.setHeader("Content-Disposition", "filename=print.pdf");
        
        try {
            String frontPath = new ClassPathResource(PATH_TTF).getFile().getAbsolutePath();
            ServletOutputStream outputStream = response.getOutputStream();
            //调用具体打印pdf方法
           String ttt = FreemarkerTemplateUtil.loadTemplateByStream(templateName, PRINT_TEMPLATE_PATH, PrintPdfUtils.class, printModel);
            if (ttt == null) {
                logger.info("打印模板出错,生成模板为空");
                return;
            }
            ITextRenderer iTextRenderer = new ITextRenderer();
            iTextRenderer.setDocumentFromString(ttt);
            ITextFontResolver fontResolver = iTextRenderer.getFontResolver();
            fontResolver.addFont(frontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextRenderer.layout();
            iTextRenderer.createPDF(outputStream);

            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            logger.info("打印模板出错", e);
        }
    }

}
